﻿using System;
using System.Net;
using System.Net.NetworkInformation;

namespace LVYAN.Utils
{
    public class WinInfo
    {
        private static string MacAddress = string.Empty;

        /// <summary>
        /// 获取MAC
        /// </summary>
        /// <returns></returns>
        public static string GetMacAddress()
        {
            if (string.IsNullOrWhiteSpace(MacAddress))
            {
                foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (nic.OperationalStatus == OperationalStatus.Up)
                    {
                        MacAddress = nic.GetPhysicalAddress().ToString();
                        Console.WriteLine($"MacAddress:{MacAddress}");
                        break; // 如果只需要获取第一个启用的网络接口的MAC地址，则可以在这里退出循环  
                    }
                }
            }
            return MacAddress;
        }
        private static string HostName = string.Empty;
        /// <summary>
        /// 计算机名称
        /// </summary>
        /// <returns></returns>
        public static string GetHostName()
        {
            if (string.IsNullOrWhiteSpace(HostName))
            {
                HostName = Dns.GetHostName();
                Console.WriteLine($"HostName:{HostName}");
            }
            return HostName;
        }
        private static string IP = string.Empty;

        /// <summary>
        /// 计算机IP
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            if (string.IsNullOrWhiteSpace(HostName))
            {
                string hostName = Dns.GetHostName(); // 获取本机主机名
                IPHostEntry ipEntry = Dns.GetHostEntry(hostName); // 根据主机名获取IP地址列表
                foreach (IPAddress ip in ipEntry.AddressList)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) // 筛选出IPv4地址
                    {
                        IP = ip.ToString();
                        Console.WriteLine($"IP:{IP}");
                        break; // 如
                    }
                }
            }
            return IP;
        }
    }
}


